class Handle{
	constructor(html_str, data){
		this.html_str = html_str;
		this.data = data;
		this.tpl_start = "{";
		this.tpl_end = "}";
		this.tags = {
			for:{},
			forin:{},
			if:{}
		}
		this.patten_var = /(\{.+\})/gm;
		this.patten_for = /(\{\$[A-Za-z0-9]+\})/gm;
		this.patten_forin = /\{forin name\=[\'|\"](.*)[\'|\"] item\=[\'|\"](.*)[\'|\"]\}\s*(.*)\s*{\/forin\}/gm;
	}
	hand(){
		let html = this.extract();
		return this.html_str;
	}
	handFor(){}
	handForin(name, item, body){
		let html = ""
		let hl = this;
		for (let k in this.data[name]){
			html+= body.replace(this.patten_var, function(match){
				return hl.handVar(match, hl.data[name][k]);
			});
		}
		return html;
	}
	handIf(){}
	handVar(match, data){
		let key = match.replace(/\{|\}/g,"");
		let v;
		if (data[key]) {
			v = data[key];
		} else {
			let arr = key.split(".");
				v = data;
			for (var i=1; i<arr.length; i++) {
				v = v[arr[i]];
			}
		}

		return v;
	}
	extract(){
		let hl = this;
		this.html_str = this.html_str.replace(this.patten_forin,function(match, name, item, body){
			return hl.handForin(name, item, body);
		});
		this.html_str = this.html_str.replace(this.patten_var,function(match){
			return hl.handVar(match, hl.data);
		});
	}
}
class TemplateBase{
	constructor(res, config){
		this.res = res;
		this.config = config;
		this.data = {}; 
	}
	output(data){
		let hl= new Handle(data, this.data);
		return hl.hand();
	}
}
module.exports = TemplateBase;